package cn.xishan.oftenporter.porter.core.annotation.sth;

import cn.xishan.oftenporter.porter.core.sysset.AutoRef;

/**
 * @author Created by https://github.com/CLovinr on 2021/8/4.
 */
class AutoRefImpl implements AutoRef {
    private Object obj;
    private Class type;
    private Listener listener;
    private Listener firstListener;

    public AutoRefImpl(Class type) {
        this.type = type;
    }

    void set(Object obj) {
        if (firstListener != null && obj != null && this.obj == null) {
            firstListener.change(obj, null);
            firstListener = null;
        }

        if (obj != this.obj) {
            Object old = this.obj;
            this.obj = obj;
            if (listener != null) {
                listener.change(obj, old);
            }
        }
    }

    @Override
    public Object get() {
        return obj;
    }

    @Override
    public Class type() {
        return type;
    }

    @Override
    public void onChange(Listener listener) {
        this.listener = listener;
    }

    @Override
    public void onFirst(Listener listener) {
        if (obj != null) {
            listener.change(obj, null);
        } else {
            this.firstListener = listener;
        }
    }
}
